<template>
  <div style="font-size: 14px">
    <!-- 添加事件弹窗 -->
    <el-drawer v-model="dialogVisible" :title="details.eno ? '事件编辑' : '事件新增'" direction="rtl" size="1000">
      <el-form ref="addForm" v-if="dialogVisible" :model="form" :rules="rules" label-width="95" v-loading="loading">
        <table v-if="!userStore.userInfo.roleCode.includes('ROLE_ENDUSER') && userStore.userInfo.job != '终端用户'">
          <tr v-if="!details.eno">
            <td>类似表单：</td>
            <td :style="{ width: '200px' }">
              <el-select v-model="similarFormCustom" @change="similarFormCustomChange">
                <el-option
                  v-for="item in similarFormCustomOptions"
                  :key="item.templateId"
                  :label="item.templateName"
                  :value="item.templateId"
                />
              </el-select>
            </td>
            <td><el-button type="primary" @click="serviceDir"> 服务目录 </el-button></td>
          </tr>
        </table>

        <el-dialog title="选择服务目录" v-model="dialogServiceDirTableVisible">
          <div :style="{ height: '500px' }">
            <el-tree
              :data="serviceSelectList"
              :props="defaultProps"
              :default-expand-all="true"
              @node-click="handleNodeClickService"
              class="custom-tree"
            />
          </div>
        </el-dialog>
        <div v-if="showCustomerForm == false">
          <div v-if="userStore.userInfo.roleCode.includes('ROLE_ENDUSER') || userStore.userInfo.job == '终端用户'">
            <el-row>
              <el-col :span="12">
                <el-form-item label="所属客户" prop="companyNo">
                  <el-select v-model="form.companyNo" placeholder="请选择所属客户" @change="companyNoChange">
                    <el-option v-for="item in orgList" :key="item.orgNo" :label="item.orgName" :value="item.orgNo" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="请求分类" prop="requestCategoryNo">
                  <el-tree-select
                    v-model="form.requestCategoryNo"
                    lazy
                    :load="cateTreeLoad"
                    :cache-data="cacheCateData"
                    check-strictly
                    :render-after-expand="false"
                    placeholder="请选择请求分类"
                    clearable
                    @change="cateChange"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="请求标题" prop="etitle">
                  <el-input v-model="form.etitle" placeholder="请输入标题" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div v-if="!userStore.userInfo.roleCode.includes('ROLE_ENDUSER') && userStore.userInfo.job != '终端用户'">
            <el-row>
              <el-col :span="12">
                <el-form-item label="所属客户" prop="companyNo">
                  <el-select v-model="form.companyNo" placeholder="请选择所属客户" @change="companyNoChange">
                    <el-option v-for="item in orgList" :key="item.orgNo" :label="item.orgName" :value="item.orgNo" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="请求用户" prop="createdByNo">
                  <!-- <el-autocomplete
				        v-model="form.createdByName"
				        :fetch-suggestions="querySearch"
				        clearable
				        placeholder="请输入用户名"
				        style="width: 100%"
				        @select="userChange"
				      >
				        <template #default="{ item }">
				          <div>{{ item.fullName }}</div>
				        </template>
				      </el-autocomplete> -->
                  <div style="display: flex; width: 100%">
                    <el-input
                      style="flex: 1; overflow: hidden"
                      v-model="form.createdByName"
                      readonly
                      placeholder="请选择用户"
                    ></el-input>
                    <el-button
                      style="margin-left: 10px"
                      type="primary"
                      :icon="Search"
                      @click="selectUser('createdByNo')"
                    ></el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="请求分类" prop="requestCategoryNo">
                  <el-tree-select
                    v-model="form.requestCategoryNo"
                    lazy
                    :load="cateTreeLoad"
                    :cache-data="cacheCateData"
                    check-strictly
                    :render-after-expand="false"
                    placeholder="请选择请求分类"
                    clearable
                    @change="cateChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="请求标题" prop="etitle">
                  <el-input v-model="form.etitle" placeholder="请输入标题" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <el-form-item label="描述" required>
            <WangEditor v-model:value="form.edesc" height="200px" />
          </el-form-item>
          <el-row v-if="!userStore.userInfo.roleCode.includes('ROLE_ENDUSER') && userStore.userInfo.job != '终端用户'">
            <el-col :span="12">
              <el-form-item label="来源">
                <el-select v-model="form.imodeNo" placeholder="请选择来源">
                  <el-option v-for="item in imodeList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级">
                <el-select v-model="form.priorityNo" placeholder="请选择优先级">
                  <el-option v-for="item in priorityList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="!userStore.userInfo.roleCode.includes('ROLE_ENDUSER') && userStore.userInfo.job != '终端用户'">
            <el-col :span="12">
              <el-form-item label="影响">
                <el-select v-model="form.effectRangeNo" placeholder="请选择影响">
                  <el-option v-for="item in effectRangeList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="复杂程度">
                <el-select v-model="form.levelNo" placeholder="请选择复杂程度">
                  <el-option v-for="item in levelList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="!userStore.userInfo.roleCode.includes('ROLE_ENDUSER') && userStore.userInfo.job != '终端用户'">
            <el-col :span="12">
              <el-form-item label="紧急度">
                <el-select v-model="form.seriousnessNo" placeholder="请选择紧急度">
                  <el-option v-for="item in seriousnessList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="位置">
                <el-tree-select
                  v-model="form.locationNos"
                  :data="positionList"
                  placeholder="请选择位置"
                  check-strictly
                  :render-after-expand="false"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <div v-if="showCustomerForm == true">
          <form-create v-model="formData" :option="option" :rule="formCreateRules" />
          <el-form style="width: 100%" label-width="122px">
            <el-form-item label="描述 :">
              <WangEditor
                v-if="edescFlag == true"
                v-model:value="customerContent"
                width="1200px"
                height="400px"
                ref="cwangEditor"
              />
            </el-form-item>
          </el-form>
          <form-create v-model="formData" :option="option2" :rule="formCreateRules2" class="custom-tree2" />
        </div>
        <el-dialog title="选择客户" v-model="dialogCustomerCompanyNoTableVisible">
          <div :style="{ height: '500px' }">
            <Custemerselect @send-data="sendCompanyNoDataCustomer" />
          </div>
        </el-dialog>
        <el-dialog title="选择用户" v-model="dialogCustomerCreatedByTableVisible">
          <div :style="{ height: '500px' }">
            <Userselect @send-data="sendCreatedByDataCustomer" :father="fatherValue" />
          </div>
        </el-dialog>

        <el-dialog title="选择请求分类" v-model="dialogRequestCategoryTableVisible">
          <div :style="{ height: '500px' }">
            <el-tree
              :data="requestCategorySelectList"
              :props="defaultProps"
              :default-expand-all="true"
              @node-click="handleNodeClickRequestCategory"
            />
            <el-button class="dialogOkBtn" type="primary" @click="submitRequestCategory" style="min-width: 80px">
              确 定
            </el-button>
          </div>
        </el-dialog>
        <el-dialog title="选择位置" v-model="dialogLocationTableVisible">
          <div :style="{ height: '500px' }">
            <el-tree
              :data="LocationSelectList"
              :props="defaultProps"
              :default-expand-all="true"
              @node-click="handleNodeClickLocation"
              class="custom-tree"
            />
            <el-button class="dialogOkBtn" type="primary" @click="submitLocation" style="min-width: 80px"> 确 定 </el-button>
          </div>
        </el-dialog>
        <el-row>
          <el-col :span="24">
            <el-tabs v-model="tabName" class="demo-tabs">
              <el-tab-pane label="附件" name="two">
                <EnclosureList v-if="details.eno" :eno="details.eno" event-type="itsm.request"></EnclosureList>
                <div v-else>
                  <el-upload ref="uploadRef" action="" :auto-upload="false" :show-file-list="false" :on-change="uploadChange">
                    <template #trigger>
                      <el-button type="primary" plain>添加附件</el-button>
                    </template>
                    <!-- <template #tip>
				                <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
				            </template> -->
                  </el-upload>
                  <el-table
                    :data="enclosureList"
                    border
                    style="margin-top: 10px"
                    :height="enclosureList.length > 0 ? '' : 100"
                    max-height="400px"
                  >
                    <el-table-column label="名称" prop="attachmentName"></el-table-column>
                    <el-table-column label="服务器路径" prop="url"></el-table-column>
                    <el-table-column label="操作" align="center" width="180">
                      <template #default="scope">
                        <el-button @click="delFile(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-tab-pane>
              <el-tab-pane
                label="关联配置项"
                name="one"
                v-if="!userStore.userInfo.roleCode.includes('ROLE_ENDUSER') && userStore.userInfo.job != '终端用户'"
              >
                <div style="margin-bottom: 10px">
                  <el-button type="primary" @click="showSelectAssetMask">添加配置项</el-button>
                </div>
                <el-table border :data="assetList" max-height="400px">
                  <el-table-column label="固定资产编号" prop="cino"></el-table-column>
                  <el-table-column label="名称" prop="ciname"></el-table-column>
                  <el-table-column label="分类" prop="categoryName"></el-table-column>
                  <el-table-column label="状态" prop="status"></el-table-column>
                  <el-table-column label="操作" width="150" align="center">
                    <template #default="scope">
                      <el-button @click="delAsset(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-drawer>
    <!-- 选择配置项（资产） -->
    <SelectAssetMask
      v-if="dialogVisible"
      ref="selectAssetMask"
      :user-name="form.createdByName"
      @change="assetChange"
    ></SelectAssetMask>
    <!-- 选择用户弹窗 -->
    <SelectUserMask ref="selectUserMask" @change="selectUserChange"></SelectUserMask>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from "vue";
import WangEditor from "@/components/WangEditor/index.vue";
import SelectAssetMask from "@/components/SelectAssetMask/index.vue";
import EnclosureList from "@/components/EnclosureList/index.vue";

import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, EditPen, View, Search } from "@element-plus/icons-vue";

import { requestAllOptions } from "@/stores/modules/event";

import {
  findPagerUserClient,
  saveRequestClient,
  updateRequest,
  findRequestByIdByClient,
  getCategoryTreeClient,
  saveRequest,
  updateRequestCustomer,
  findAllTemplate
} from "@/api/modules/eventManagement";
import { findAllEventAttachment, uploadAttr } from "@/api/modules/common";
import { useUserStore } from "@/stores/modules/user";
import { dataDictionaryItemsfindByCode, getCategoryTreeAllData } from "@/api/modules/dataDictionary";
import { findFormCustomById, findCiByIds } from "@/api/modules/systemTools";
import Custemerselect from "@/views/tools/custemerSelect/index.vue";
import { Base64 } from "js-base64";
import Userselect from "@/views/tools/userSelectbyOrgNo/index.vue";
import SelectUserMask from "@/components/SelectUserMask/index.vue";

const userStore = useUserStore();

const allOptions = requestAllOptions();

const details = ref<any>({});

const tabName = ref("two");

interface OrgItem {
  orgNo: string;
  orgName: string;
}
interface Tree {
  label: string;
  children?: Tree[];
  attr: any;
}

//请求内容模板
const similarFormCustom = ref();
const similarFormCustomOptions = ref<any>([]);
const similarFormCustomChange = (data: any) => {
  let tmpDefaultFormCreateRules = [];
  enclosureList.value = [];
  similarFormCustomOptions.value.forEach(item => {
    console.log(item);
    console.log(data);
    if (data == item.templateId) {
      console.log("选择");
      console.log(item);
      let newParams = JSON.parse(item.templateJson);
      console.log("jsion");
      console.log(newParams);
      //自定义表单
      if (item.formId != "" && item.formId != 0 && item.formId != undefined) {
        form.formId = item.formId;
        findFormCustomById(item.formId).then(resFindFormCustom => {
          dataFlagObj.value = [];
          showCustomerForm.value = true;
          edescFlag.value = false;
          let newResFindFormCustom = JSON.parse(JSON.stringify(resFindFormCustom));
          let yyde = Base64.decode(newResFindFormCustom.formCustomContents); //解密
          console.log(yyde);
          let a = JSON.parse(yyde);
          let formCreateRulesArray: any[] = [];
          let formCreateRules2Array: any[] = [];

          for (let i = 0; i < a.length; i++) {
            if (a[i].label != undefined && a[i].label != "") {
              showCustomerForm.value = false;
              break;
            }
            console.log(a[i]);
            if (a[i].title == "所属客户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCustomerCompanyNoTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "请求分类") {
              a[i]["on"] = {
                focus(inject) {
                  dialogRequestCategoryTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "请求用户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCustomerCreatedByTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "位置") {
              a[i]["on"] = {
                focus(inject) {
                  dialogLocationTableVisible.value = true;
                }
              };
            }

            if (a[i].attrdataDictionary != null && a[i].attrdataDictionary != undefined && a[i].attrdataDictionary != "") {
              dataFlagObj.value.push(a[i]);
              //优先级priority
              dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
                let optionList = [];
                (res as any).forEach(function (element) {
                  // element["label"] = element["dname"];
                  // element["value"] = element["dname"];
                  //optionList.push({label:element["dname"],value:element["dcode"]})
                  a[i].options.push({ label: element["dname"], value: element["dcode"] });
                });
                // a[i].options=optionList
              });
            }

            if (a[i].title == "描述") {
              edescFlag.value = true;
              continue;
            }
            if (edescFlag.value == false) {
              formCreateRulesArray.push(a[i] as any);
            } else {
              formCreateRules2Array.push(a[i] as any);
            }
          }
          formCreateRules.value = formCreateRulesArray;
          formCreateRules2.value = formCreateRules2Array;

          let attrVals = newParams.attrVals == undefined ? {} : newParams.attrVals;
          console.log("555555555555555");
          console.log(newParams);
          console.log(newParams.requestCategoryName);
          setTimeout(() => {
            formData.value.creator = newParams.creator == undefined ? "" : newParams.creator;

            formData.value.approvalNo = newParams.approvalNo == undefined ? "" : newParams.approvalNo;

            formData.value.etitle = newParams.etitle == undefined ? "" : newParams.etitle;
            formData.value.companyName = newParams.companyName == undefined ? "" : newParams.companyName;
            formData.value.companyNo = newParams.companyNo == undefined ? 1 : newParams.companyNo;
            formData.value.createdByName = newParams.createdByName == undefined ? "" : newParams.createdByName;
            formData.value.createdByNo = newParams.createdByNo == undefined ? "" : newParams.createdByNo;
            formData.value.requestCategoryName = newParams.requestCategoryName == undefined ? "" : newParams.requestCategoryName;
            formData.value.requestCategoryNo = newParams.requestCategoryNo == undefined ? "" : newParams.requestCategoryNo;
            //requestCategorySelectValue.value=data.requestCategoryName==undefined?"":data.requestCategoryName;
            //addRequestTemplateFormData.edesc= data.edesc==undefined?"":data.edesc;
            customerContent.value = newParams.edesc == undefined ? "" : newParams.edesc;
            // imodeSelectValue prioritySelectValue effectRangeSelectValue levelSelectValue seriousnessSelectValue LocationSelectValue
            formData.value.imodeNo = newParams.imodeNo == undefined ? "" : newParams.imodeNo;
            formData.value.priorityNo = newParams.priorityNo == undefined ? "" : newParams.priorityNo;
            formData.value.effectRangeNo = newParams.effectRangeNo == undefined ? "" : newParams.effectRangeNo;
            formData.value.levelNo = newParams.levelNo == undefined ? "" : newParams.levelNo;
            formData.value.seriousnessNo = newParams.seriousnessNo == undefined ? "" : newParams.seriousnessNo;
            formData.value.locationName = newParams.locationName == undefined ? "" : newParams.locationName;
            formData.value.locationNos = newParams.locationNos == undefined ? "" : newParams.locationNos;
            console.log("ssssssssssssssssssssssssssssssssssssssssssssssssssss");
            console.log(attrVals);
            console.log(dataFlagObj.value);
            Object.keys(attrVals).forEach(key => {
              for (let i = 0; i < dataFlagObj.value.length; i++) {
                if (dataFlagObj.value[i].title == key) {
                  let eavKey = dataFlagObj.value[i].field;
                  if (`${attrVals[key]}` == "true") {
                    formData.value[eavKey] = true;
                  } else {
                    console.log("sssssssssss");
                    console.log(`${attrVals[key]}`);
                    if (!Number.isNaN(Number(`${attrVals[key]}`))) {
                      if (`${attrVals[key]}` == "") {
                        formData.value[eavKey] = `${attrVals[key]}`;
                      } else {
                        //数字
                        formData.value[eavKey] = parseInt(`${attrVals[key]}`);
                      }
                    } else {
                      //非数字
                      formData.value[eavKey] = `${attrVals[key]}`;
                    }
                  }
                }
              }
              //非数据回显
              Object.keys(formData.value).forEach(formDatakey => {
                if (key == formDatakey) {
                  if (`${attrVals[key]}` == "true") {
                    formData.value[key] = true;
                  } else {
                    if (!Number.isNaN(Number(`${attrVals[key]}`))) {
                      if (`${attrVals[key]}` == "") {
                        formData.value[key] = `${attrVals[key]}`;
                      } else {
                        //数字
                        formData.value[key] = parseInt(`${attrVals[key]}`);
                      }
                    } else {
                      //非数字
                      formData.value[key] = `${attrVals[key]}`;
                    }
                  }
                }
              });
              let ciIds = "";
              for (let i = 0; i < newParams.relatedCiNos.length; i++) {
                if (ciIds == "") {
                  ciIds = "?ids=" + newParams.relatedCiNos[i];
                } else {
                  ciIds += "&ids=" + newParams.relatedCiNos[i];
                }
              }
              findCiByIds(ciIds).then(ciRes => {
                if (ciRes != null) {
                  (ciRes as any).forEach(function (element) {
                    assetList.value.push(element);
                  });
                }
              });
              let valArr = newParams.attachmentStr.split("-s-");
              console.log("uuuuuuuuuuuuuuuuu");
              console.log(valArr);
              enclosureList.value = [];
              for (let i = 0; i < valArr.length; i++) {
                if (valArr[i] == "") {
                  continue;
                }
                let attObj = valArr[i].split("==");
                let attachment = {
                  attachmentName: attObj[0],
                  url: attObj[1],
                  size: attObj[2]
                };
                enclosureList.value.push(attachment);
              }
              if (newParams.serviceNos != null) {
                form.serviceDirIds = Object.keys(newParams.serviceNos)[0];
              }
            });
          }, 1500);
        });
      } else {
        console.log("dsssssssssssssss");

        console.log(newParams.serviceNos);
        console.log(Object.keys(newParams.serviceNos)[0]);
        if (newParams.serviceNos != null) {
          console.log("dsssssssssssssss");
          newParams.serviceDirIds = Object.keys(newParams.serviceNos)[0];
        }
        console.log(newParams);
        showCustomerForm.value = false;
        Object.keys(formData.value).forEach(key => {
          formData.value[key] = "";
        });
        let ciIds = "";
        for (let i = 0; i < newParams.relatedCiNos.length; i++) {
          if (ciIds == "") {
            ciIds = "?ids=" + newParams.relatedCiNos[i];
          } else {
            ciIds += "&ids=" + newParams.relatedCiNos[i];
          }
        }

        let cilistTmp: any[] = [];
        findCiByIds(ciIds).then(ciRes => {
          if (ciRes != null) {
            (ciRes as any).forEach(function (element) {
              cilistTmp.push(element as any);
            });
          }
          newParams["cigDTO"] = cilistTmp;
          updateData(newParams);
        });
      }

      let valArr = newParams.attachmentStr.split("-s-");
      enclosureList.value = [];
      for (let i = 0; i < valArr.length; i++) {
        if (valArr[i] == "") {
          continue;
        }
        let attObj = valArr[i].split("==");
        let attachment = {
          attachmentName: attObj[0],
          url: attObj[1],
          size: attObj[2]
        };
        enclosureList.value.push(attachment);
      }
    }
  });
};
//内容模板结束
onMounted(() => {
  //请求分类选择树
  getCategoryTreeAllData("Request").then(res => {
    requestCategorySelectList.value = [res as any];
  });

  //位置
  getCategoryTreeAllData("Location").then(res => {
    LocationSelectList.value = [res as any];
  });
  findAllTemplate().then(res => {
    console.log(res);
    similarFormCustomOptions.value = res as any;
  });
});

//服务目录
const fatherValue = ref({ orgNo: 1 });
const dialogServiceDirTableVisible = ref(false);
const requestCategorySelectList = ref<any>([]);
const LocationSelectList = ref<any>([]);
// 服务目录
const serviceDir = async () => {
  getCategoryTreeAllData("Service").then(res => {
    // 使用traverseTree遍历树
    // traverseTree(res as any, node => {
    //   node["lable"] = node.attr.cname;
    //   node["value"] = node.attr.cname;
    // });
    serviceSelectList.value = [res as any];
    dialogServiceDirTableVisible.value = true;
  });
};
const serviceSelectList = ref<any>([]);
const defaultProps = {
  children: "children",
  label: "data"
};
const showCustomerForm = ref(false);
const edescFlag = ref(false);
const formCreateRules = ref<any>([]);
const formCreateRules2 = ref<any>([]);
const option = ref({
  submitBtn: false
});
const option2 = ref({
  submitBtn: false
});
const customerContent = ref("");
const handleNodeClickService = (data: Tree) => {
  ElMessageBox.confirm("您输入的数据将不会被保存，确定切换表单？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      form.serviceDirIds = data.attr.id;
      dialogServiceDirTableVisible.value = false;
      if (data.attr.formId != null && data.attr.formId != undefined) {
        form.formId = data.attr.formId;
        showCustomerForm.value = true;
        findFormCustomById(data.attr.formId).then(res => {
          edescFlag.value = false;
          let newParams = JSON.parse(JSON.stringify(res));
          let yyde = Base64.decode(newParams.formCustomContents); //解密
          let a = JSON.parse(yyde);
          console.log(a);
          let formCreateRulesArray: any[] = [];
          let formCreateRules2Array: any[] = [];

          for (let i = 0; i < a.length; i++) {
            if (a[i].label != undefined && a[i].label != "") {
              showCustomerForm.value = false;
              break;
            }
            if (a[i].title == "所属客户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCustomerCompanyNoTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "请求分类") {
              a[i]["on"] = {
                focus(inject) {
                  dialogRequestCategoryTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "请求用户") {
              a[i]["on"] = {
                focus(inject) {
                  dialogCustomerCreatedByTableVisible.value = true;
                }
              };
            }
            if (a[i].title == "位置") {
              a[i]["on"] = {
                focus(inject) {
                  dialogLocationTableVisible.value = true;
                }
              };
            }
            // if (a[i].title == "优先级") {
            // 	console.log("uuuuuuuuuu")

            // 	console.log(a[i]["options"])
            // 	console.log(a[i].attrdataDictionary)
            //  dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
            // 	 console.log("988888888877777777777")

            // 	 console.log(res)
            //    (res as any).forEach(function (element) {
            //      // element["label"] = element["dname"];
            //      // element["value"] = element["dname"];
            //      //optionList.push({label:element["dname"],value:element["dcode"]})
            //      a[i].options.push({ label: element["dname"], value: element["dcode"] });
            // 	 console.log("uuuuuuuuuu")

            // 	 console.log(a[i]["options"])
            //    });
            //  });
            // }
            if (a[i].attrdataDictionary != null && a[i].attrdataDictionary != undefined) {
              let optionList = [];
              //优先级priority
              dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
                (res as any).forEach(function (element) {
                  // element["label"] = element["dname"];
                  // element["value"] = element["dname"];
                  //optionList.push({label:element["dname"],value:element["dcode"]})
                  a[i].options.push({ label: element["dname"], value: element["dcode"] });
                });
              });
            }

            if (a[i].title == "描述") {
              edescFlag.value = true;
              continue;
            }
            if (edescFlag.value == false) {
              formCreateRulesArray.push(a[i] as any);
            } else {
              formCreateRules2Array.push(a[i] as any);
            }
          }
          formCreateRules.value = formCreateRulesArray;
          formCreateRules2.value = formCreateRules2Array;
        });
      } else {
        form.formId = "";
        showCustomerForm.value = false;
      }
    })
    .catch(e => {
      console.log(e);
      ElMessage({
        type: "info",
        message: "取消操作"
      });
    });
};
const cwangEditor = ref(null);
const dialogCustomerCompanyNoTableVisible = ref(false);
const dialogCustomerCreatedByTableVisible = ref(false); //创建人
const dialogLocationTableVisible = ref(false);
const dialogRequestCategoryTableVisible = ref(false);
const requestCategoryCustomerSelectValue = ref();
const requestCategoryCustomerSelectList = ref<any>([]);
const locationCustomerSelectValue = ref();
const locationCustomerSelectList = ref<any>([]);
const handleNodeClickRequestCategory = (data: any) => {
  console.log(data);
  requestCategoryCustomerSelectValue.value = data;
};
const handleNodeClickLocation = (data: any) => {
  console.log(data);
  locationCustomerSelectValue.value = data;
};
const submitRequestCategory = () => {
  if (requestCategoryCustomerSelectValue.value == null || requestCategoryCustomerSelectValue.value == undefined) {
    ElMessage.info("请选择请求分类");
    return;
  }
  if ((requestCategoryCustomerSelectValue.value.children as any).length > 0) {
    ElMessage.info("请选择叶子节点");
    return;
  }
  formData.value.requestCategoryName = requestCategoryCustomerSelectValue.value.attr.cname;
  formData.value.requestCategoryNo = requestCategoryCustomerSelectValue.value.attr.id;
  if (cwangEditor.value != null) {
    (cwangEditor.value["editor"] as any).focus();
  }

  dialogRequestCategoryTableVisible.value = false;
};

const submitLocation = () => {
  if (locationCustomerSelectValue.value == null || locationCustomerSelectValue.value == undefined) {
    ElMessage.info("请选择位置");
    return;
  }
  if ((locationCustomerSelectValue.value.children as any).length > 0) {
    ElMessage.info("请选择叶子节点");
    return;
  }
  formData.value["locationName"] = locationCustomerSelectValue.value.attr.cname;
  formData.value["locationNos"] = locationCustomerSelectValue.value.attr.id;
  if (cwangEditor.value != null) {
    (cwangEditor.value["editor"] as any).focus();
  }
  dialogLocationTableVisible.value = false;
};
const formData = ref<any>({
  createdByNo: "",
  etitle: "",
  requestCategoryNo: "",
  companyNo: "",
  creator: "",
  approvalNo: "",
  companyName: "",
  createdByName: "",
  requestCategoryName: "",
  imodeNo: "",
  priorityNo: "",
  effectRangeNo: "",
  levelNo: "",
  seriousnessNo: "",
  locationName: "",
  locationNos: ""
});
//客户选择子组件弹窗回调方法
const sendCompanyNoDataCustomer = (data: any) => {
  formData.value["companyName"] = data.orgName;
  formData.value["companyNo"] = data.orgNo;
  (cwangEditor.value as any).editor.focus();
  dialogCustomerCompanyNoTableVisible.value = false;
};
//用户选择子组件弹窗回调方法
const sendCreatedByDataCustomer = (data: any) => {
  formData.value["createdByNo"] = data.userId;
  formData.value["createdByName"] = data.fullName;
  (cwangEditor.value as any).editor.focus();
  dialogCustomerCreatedByTableVisible.value = false;
};

// 所属客户列表
const orgList = computed(() => {
  let list = ref<OrgItem[]>(allOptions.orgList || []);
  let companyNo = userStore.userInfo.companyNo;
  let hasItem = false;
  list.value.forEach((item: any) => {
    if (item.orgNo === companyNo) {
      hasItem = true;
    }
  });
  if (!hasItem) {
    list.value.push({
      orgName: userStore.userInfo.companyName,
      orgNo: userStore.userInfo.companyNo
    });
  }
  return list.value;
});

interface UniversalItem {
  id: number;
  label: string;
  cname: string;
  dname: string;
  dcode: string;
}

// 分类列表
const cateList = computed<any[]>(() => {
  let list = JSON.parse(JSON.stringify(allOptions.cateList));
  console.log("hhhhhhhhhhhhhhhh");
  console.log(list);
  list.forEach((item: any) => {
    item.label = item.attr.cname;
    item.value = item.attr.id;
    if (item.children && item.children.length > 0) {
      item.children.forEach((vo: any) => {
        vo.label = vo.attr.cname;
        vo.value = vo.attr.id;
      });
    }
  });
  return list;
});

// 来源列表
const imodeList = computed<UniversalItem[]>(() => {
  return allOptions.imodeList;
});

// 优先级列表
const priorityList = computed<UniversalItem[]>(() => {
  return allOptions.priorityList;
});

// 影响列表
const effectRangeList = computed<UniversalItem[]>(() => {
  return allOptions.effectRangeList;
});

// 复杂程度表
const levelList = computed<UniversalItem[]>(() => {
  return allOptions.levelList;
});

// 紧急度列表
const seriousnessList = computed(() => {
  return allOptions.seriousnessList;
});

interface PositionItem {
  attr: UniversalItem;
  children: PositionItem[];
}

// 位置列表
const positionList = computed(() => {
  let list: any[] = JSON.parse(JSON.stringify(allOptions.positionList));
  list.forEach((item: any) => {
    item.label = item.attr.cname;
    item.value = item.attr.id;
    if (item.children.length > 0) {
      item.children.forEach((vo: any) => {
        vo.label = vo.attr.cname;
        vo.value = vo.attr.id;
      });
    }
  });
  return list;
});

const userList = ref<any[]>([]);

const dialogVisible = ref(false);

type Form = {
  companyNo: string | number;
  createdByNo: string | number;
  createdByName: string;
  requestCategoryNo: string | number;
  requestCategoryName: string;
  etitle: string;
  edesc: string;
  imodeNo: string | number;
  priorityNo: string | number;
  effectRangeNo: string | number;
  levelNo: string | number;
  seriousnessNo: string | number;
  locationNos: string;
  attachmentStr: string; // 附件
  requestCode: string;
  formId: string; //表单id
  serviceDirIds: string;
};

const form = reactive<Form>({
  companyNo: "",
  createdByNo: "",
  createdByName: "",
  requestCategoryNo: "",
  requestCategoryName: "",
  etitle: "",
  edesc: "",
  imodeNo: "",
  priorityNo: "",
  effectRangeNo: "",
  levelNo: "",
  seriousnessNo: "",
  locationNos: "",
  attachmentStr: "", // 附件
  requestCode: "",
  formId: "", //表单id
  serviceDirIds: ""
});
const rules = reactive({
  companyNo: [{ required: true, message: "请选择所属客户", trigger: "change" }],
  createdByNo: [{ required: true, message: "请选择请求用户", trigger: "change" }],
  requestCategoryNo: [{ required: true, message: "请选择请求分类", trigger: "change" }],
  etitle: [{ required: true, message: "请输入请求标题", trigger: "blur" }]
});

// 打开选择用户弹窗
const selectUserMask = ref();
const selectUserType = ref("");
const selectUser = (type: string) => {
  selectUserType.value = type;
  selectUserMask.value.open();
};

// 选择用户
const selectUserChange = (user: { userId: string | number; fullName: string }) => {
  console.log(user);
  if (selectUserType.value == "createdByNo") {
    form.createdByNo = user.userId;
    form.createdByName = user.fullName;
  }
};

// 获取请求人列表
const timer = ref();
const getRequestUserList = (no, name) => {
  clearTimeout(timer.value);
  timer.value = setTimeout(() => {
    clearTimeout(timer.value);
    findPagerUserClient({
      "userQueryDto.companyNo": form.companyNo,
      "userQueryDto.loginName": "",
      Sord: "desc",
      sidx: "userId",
      _search: false,
      page: 1,
      rows: 100
    }).then((res: any) => {
      let list = res.data || [];
      list.forEach(item => {
        item.value = item.userId;
      });
      userList.value = list;
      if (no && name) {
        form.requestCategoryNo = no;
        form.requestCategoryName = name;
      }
    });
  }, 100);
};

const companyNoChange = () => {
  // form.createdByNo = "";
  // form.createdByName = "";
  // userList.value = [];
  // getRequestUserList(null, null); // 获取请求人列表
};

const querySearch = (queryString: string, cb: any) => {
  let arr: any[] = [];
  userList.value.forEach(item => {
    if (item.fullName.indexOf(queryString) >= 0) {
      arr.push(item);
    }
  });
  cb(arr);
};

// 修改请求人
const userChange = (item: any) => {
  form.createdByNo = item.value;
  form.createdByName = item.fullName;
};

// 查询分类树
const cateTreeLoad = (node, resolve) => {
  console.log("dddddddddddddddddddddddddddddddssss");
  console.log(node.level);
  console.log(cateList.value);
  if (node.level == 0) {
    console.log("ssssssssssssssss");
    resolve(cateList.value);
  } else {
    // 获取分类列表
    getCategoryTreeClient({
      types: "request",
      parentEventId: node.data.value
    }).then((res: any) => {
      res.forEach(item => {
        item.label = item.attr.cname;
        item.value = item.attr.id;
      });
      resolve(res);
    });
  }
};

// 查询树中的某项
const findEmployeeById = (arr: any[], value: any) => {
  for (let item of arr) {
    if (item.value && item.value === value) {
      return item;
    }
    if (item.id && item.id === value) {
      return item;
    }
    if (item.children && Array.isArray(item.children)) {
      const result = findEmployeeById(item.children, value);
      if (result) {
        return result;
      }
    }
  }
  return null;
};

// 修改分类
const cateChange = (e: any) => {
  const data = findEmployeeById(cateList.value, e);
  if (data != null) {
    form.requestCategoryName = data.label;
  }
};

// 选择配置项
const selectAssetMask = ref();
const showSelectAssetMask = () => {
  selectAssetMask.value?.open();
};
const assetList = ref<any[]>([]);
const assetChange = list => {
  list.forEach(data => {
    let has_item = false;
    assetList.value.forEach(item => {
      if (item.ciId == data.ciId) {
        has_item = true;
      }
    });
    // ElMessage.warning("已选择该资产，无需重复选择");
    if (!has_item) {
      assetList.value.push(data);
    }
  });
};
// 删除配置项
const delAsset = item => {
  let index = 0;
  assetList.value.forEach((vo, idx) => {
    if (vo.ciId == item.ciId) {
      index = idx;
    }
  });
  assetList.value.splice(index, 1);
};

const enclosureList = ref<any[]>([]); // 附件列表

const getEnclosureList = () => {
  findAllEventAttachment({
    "eventAttachmentDto.eno": details.value.eno,
    "eventAttachmentDto.eventType": "itsm.request"
  }).then((res: any) => {
    enclosureList.value = res || [];
  });
};

import type { UploadProps } from "element-plus";
// 上传附件
const uploadChange: UploadProps["onChange"] = (uploadFile: any) => {
  loading.value = true;
  let params = new FormData();
  params.append("filedata", uploadFile.raw);
  uploadAttr("yuehaishuiwu_zhengshi", params)
    .then(res => {
      loading.value = false;
      enclosureList.value.push({
        attachmentName: uploadFile.name,
        url: res.msg,
        size: uploadFile.size
      });
    })
    .catch(() => {
      loading.value = false;
    });
};

// 删除附件
const delFile = item => {
  ElMessageBox.confirm("确定要删除该附件？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      let index = -1;
      enclosureList.value.forEach((vo, idx) => {
        if (vo.url === item.url) {
          index = idx;
        }
      });
      if (index >= 0) {
        enclosureList.value = [];
        let list = [...enclosureList.value];
        list[index].splice(index, 1);
        enclosureList.value = list;
      }
    })
    .catch(() => {
      // cancel operation
    });
};

// 定义 emit 事件
const emit = defineEmits<{
  change: [];
  add: [];
}>();

const addForm = ref();
const submit = async () => {
  if (showCustomerForm.value == true) {
    console.log(form);
    //自定义表单
    console.log(formData.value);
    if (customerContent.value == null || customerContent.value == "") {
      ElMessage({
        customClass: "customMsgCls",
        message: "描述不能为空",
        type: "error"
      });
      return;
    }
    form.edesc = customerContent.value.toString();
    if (formData.value.companyNo == null || formData.value.companyNo == "") {
      ElMessage({
        customClass: "customMsgCls",
        message: "请选择所属客户",
        type: "error"
      });
      return;
    }
    if (formData.value.createdByNo == null || formData.value.createdByNo == "") {
      ElMessage({
        customClass: "customMsgCls",
        message: "请选择用户",
        type: "error"
      });

      return;
    }
    if (formData.value.etitle == null || formData.value.etitle == "") {
      ElMessage({
        customClass: "customMsgCls",
        message: "标题不能为空",
        type: "error"
      });

      return;
    }
    if (formData.value.requestCategoryNo == null || formData.value.requestCategoryNo == "") {
      ElMessage({
        customClass: "customMsgCls",
        message: "分类不能为空",
        type: "error"
      });

      return;
    }
    //数据拷贝
    Object.keys(formData.value).forEach(key => {
      form[`${key}`] = `${formData.value[key]}`;
    });
    // 关联的配置项
    let ciIds = ref<any[]>([]);
    assetList.value.forEach(item => {
      ciIds.value.push("cinos=" + item.ciId);
    });
    // 组装数据（关联的配置项）
    let ciIdsText = "";
    if (ciIds.value.length > 0) {
      ciIdsText = ciIds.value.join("&");
    }
    if (ciIdsText != "") {
      ciIdsText = "?" + ciIdsText;
    }
    if (details.value.eno) {
      console.log("编辑");
      // 自定义表单编辑
      // 附件
      let attachmentStr = "";
      if (enclosureList.value.length > 0) {
        enclosureList.value.forEach(item => {
          attachmentStr += item.attachmentName + "==" + item.url + "==" + item.size + "-s-";
        });
      }

      form["creator"] = userStore.username;
      form["eno"] = details.value.eno;
      form["technicianName"] = userStore.username;
      form["attachmentStr"] = attachmentStr;
      updateRequestCustomer(form, "requestDTO", ciIdsText).then(res => {
        ElMessage.success("编辑成功");
        dialogVisible.value = false;
        emit("change");
      });
    } else {
      // 自定义表单新增
      // 附件
      let attachmentStr = "";
      if (enclosureList.value.length > 0) {
        enclosureList.value.forEach(item => {
          attachmentStr += item.attachmentName + "==" + item.url + "==" + item.size + "-s-";
        });
      }

      form["creator"] = userStore.username;
      (form["technicianName"] = userStore.username), (form["attachmentStr"] = attachmentStr);
      saveRequest(form, "requestDTO", ciIdsText).then(res => {
        ElMessage.success("保存成功");
        dialogVisible.value = false;
        emit("add");
      });
    }
  } else {
    //非自定义表单
    await addForm.value.validate((valid, fields) => {
      if (valid) {
        if (!form.edesc) {
          ElMessage.warning("请输入描述");
          return false;
        }
        // 关联的配置项
        let ciIds = ref<any[]>([]);
        assetList.value.forEach(item => {
          ciIds.value.push("cinos=" + item.ciId);
        });
        // 组装数据（关联的配置项）
        let ciIdsText = "";
        if (ciIds.value.length > 0) {
          ciIdsText = ciIds.value.join("&");
        }
        if (details.value.eno) {
          // 编辑
          const data = new FormData();
          data.append("requestDTO.actionName", "编辑");
          data.append("requestDTO.eno", details.value.eno || "");
          data.append("requestDTO.creator", userStore.username || "");
          data.append("requestDTO.companyNo", "" + form.companyNo || "");
          data.append("requestDTO.createdByNo", "" + form.createdByNo || "");
          data.append("requestDTO.createdByName", form.createdByName || "");
          data.append("requestDTO.requestCategoryNo", "" + form.requestCategoryNo || "");
          data.append("requestDTO.requestCategoryName", form.requestCategoryName || "");
          data.append("requestDTO.etitle", form.etitle || "");
          data.append("requestDTO.edesc", form.edesc || "");
          data.append("requestDTO.imodeNo", "" + form.imodeNo || "");
          data.append("requestDTO.priorityNo", "" + form.priorityNo || "");
          data.append("requestDTO.effectRangeNo", "" + form.effectRangeNo || "");
          data.append("requestDTO.levelNo", "" + form.levelNo || "");
          data.append("requestDTO.seriousnessNo", "" + form.seriousnessNo || "");
          data.append("requestDTO.locationNos", form.locationNos || "");
          data.append("requestDTO.ciId", details.value.ciId || "");
          data.append("requestDTO.pid", details.value.pid || "");
          data.append("requestDTO.statusNo", details.value.statusNo || "");
          data.append("requestDTO.requestCode", details.value.requestCode || "");
          if (form.serviceDirIds != null && form.serviceDirIds != "")
            data.append("requestDTO.serviceDirIds", form.serviceDirIds || "");
          updateRequest(ciIdsText, data)
            .then(() => {
              ElMessage.success("保存成功");
              dialogVisible.value = false;
              emit("change");
            })
            .catch(err => {
              ElMessage.error(err.msg || err.message || err.data || "提交失败");
            });
        } else {
          // 新增
          // 附件
          let attachmentStr = "";
          if (enclosureList.value.length > 0) {
            enclosureList.value.forEach(item => {
              attachmentStr += item.attachmentName + "==" + item.url + "==" + item.size + "-s-";
            });
          }
          saveRequestClient(ciIdsText, {
            "requestDTO.creator": userStore.username,
            "requestDTO.technicianName": userStore.username,
            "requestDTO.companyNo": form.companyNo,
            "requestDTO.createdByNo": form.createdByNo,
            "requestDTO.createdByName": form.createdByName,
            "requestDTO.requestCategoryNo": form.requestCategoryNo,
            "requestDTO.requestCategoryName": form.requestCategoryName,
            "requestDTO.etitle": form.etitle,
            "requestDTO.edesc": form.edesc,
            "requestDTO.imodeNo": form.imodeNo,
            "requestDTO.priorityNo": form.priorityNo,
            "requestDTO.effectRangeNo": form.effectRangeNo,
            "requestDTO.levelNo": form.levelNo,
            "requestDTO.seriousnessNo": form.seriousnessNo,
            "requestDTO.locationNos": form.locationNos,
            "requestDTO.attachmentStr": attachmentStr, // 附件
            "requestDTO.serviceDirIds": form.serviceDirIds || "" // 附件
          })
            .then(() => {
              ElMessage.success("保存成功");
              dialogVisible.value = false;
              emit("add");
            })
            .catch(err => {
              ElMessage.error(err.msg || err.message || err.data || "提交失败");
            });
        }
      } else {
        console.log("error submit!", fields);
      }
    });
  }
};

const cacheCateData = ref<any[]>([]);
const loading = ref(false);
const dataFlagObj = ref<any[]>([]);

// 清空表单数据
const clearAllFormData = () => {
  details.value = {};
  form.companyNo = "";
  form.requestCategoryNo = "";
  form.requestCategoryName = "";
  form.etitle = "";
  form.edesc = "";
  form.imodeNo = "";
  form.priorityNo = "";
  form.effectRangeNo = "";
  form.levelNo = "";
  form.seriousnessNo = "";
  form.locationNos = "";
  enclosureList.value = [];
  assetList.value = [];
  tabName.value = "two";
};

watch(
  () => dialogVisible.value,
  val => {
    clearAllFormData();
  }
);

const open = (item: any) => {
  console.log(item);
  details.value = {};
  form.serviceDirIds = "";
  form.companyNo = "";
  form.requestCategoryNo = "";
  form.requestCategoryName = "";
  form.etitle = "";
  form.edesc = "";
  form.imodeNo = "";
  form.priorityNo = "";
  form.effectRangeNo = "";
  form.levelNo = "";
  form.seriousnessNo = "";
  form.locationNos = "";
  enclosureList.value = [];
  assetList.value = [];
  tabName.value = "one";

  if (item) {
    console.log("isTanpingAdd");
    console.log(item.isTanpingAdd);
    if (item.isTanpingAdd != undefined) {
      console.log("isTanpingAdd");
      console.log(item.isTanpingAdd);
      //弹屏新增
      showCustomerForm.value = false;
      //数据清空
      Object.keys(formData.value).forEach(key => {
        formData.value[`${key}`] = "";
      });
      form.edesc = "";
      customerContent.value = "";
      // 新增
      details.value = {};
      // form.companyNo = item.companyNo || "";
      form.createdByNo = item.userId || "";
      form.createdByName = item.fullName || "";
      console.log("form");
      console.log(form);
    } else {
      showCustomerForm.value = false;
      // 编辑
      details.value = item;
      form.companyNo = item.companyNo || "";
      // getEnclosureList(); // 获取附件列表
      loading.value = true;
      findRequestByIdByClient({
        "requestQueryDTO.eno": item.eno
      })
        .then(res => {
          loading.value = false;
          updateData(res);
        })
        .catch(() => {
          loading.value = false;
        });
    }
  } else {
    showCustomerForm.value = false;
    //数据清空
    Object.keys(formData.value).forEach(key => {
      formData.value[`${key}`] = "";
    });
    form.edesc = "";
    customerContent.value = "";
    // 新增
    details.value = {};
    setTimeout(() => {
      form.companyNo = userStore.userInfo.companyNo || "";
    }, 1500);

    form.createdByNo = userStore.userInfo.userId || "";
    form.createdByName = userStore.userInfo.fullName || "";
  }
  getRequestUserList(null, null); // 获取请求人列表
  dialogVisible.value = true;

  if (
    orgList.value.length == 0 ||
    cateList.value.length == 0 ||
    imodeList.value.length == 0 ||
    priorityList.value.length == 0 ||
    effectRangeList.value.length == 0 ||
    levelList.value.length == 0 ||
    seriousnessList.value.length == 0
  ) {
    allOptions.getAllOptions();
  }
};

const updateData = data => {
  details.value = data;
  form.companyNo = data.companyNo || "";
  form.createdByNo = data.createdByNo || "";
  form.createdByName = data.createdByName || "";
  form.requestCategoryNo = data.requestCategoryNo || "";
  form.requestCategoryName = data.requestCategoryName || "";
  form.requestCode = data.requestCode || "";
  form.serviceDirIds = data.serviceDirIds || "";
  console.log("form.serviceDirIds");
  console.log(form.serviceDirIds);
  console.log(data.serviceDirIds);
  cacheCateData.value = [
    {
      label: form.requestCategoryName,
      value: form.requestCategoryNo
    }
  ];
  form.etitle = data.etitle || "";
  if (data.edesc) {
    form.edesc = data.edesc
      .replace(
        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
        ""
      )
      .trim();
    console.log(form.edesc);
  } else {
    form.edesc = "";
  }
  form.imodeNo = data.imodeNo || "";
  form.priorityNo = data.priorityNo || "";
  form.effectRangeNo = data.effectRangeNo || "";
  form.levelNo = data.levelNo || "";
  form.seriousnessNo = data.seriousnessNo || "";
  let tmpServiceDirIds = data.serviceDirectory || "";
  if (tmpServiceDirIds != "" && tmpServiceDirIds.length > 0) {
    form.serviceDirIds = tmpServiceDirIds[0].eventId;
  }

  if (data.locationNos) {
    form.locationNos = "" + data.locationNos;
  } else {
    form.locationNos = "";
  }
  assetList.value = data.cigDTO;
  //自定义表单
  if (data.formId != "" && data.formId != undefined && data.formId != 0) {
    console.log("ssssssssssssssssssssssssssss");
    form.formId = data.formId;
    findFormCustomById(data.formId).then(resFindFormCustom => {
      dataFlagObj.value = [];
      showCustomerForm.value = true;
      edescFlag.value = false;
      let newResFindFormCustom = JSON.parse(JSON.stringify(resFindFormCustom));
      let yyde = Base64.decode(newResFindFormCustom.formCustomContents); //解密
      console.log(yyde);
      let a = JSON.parse(yyde);
      let formCreateRulesArray: any[] = [];
      let formCreateRules2Array: any[] = [];

      for (let i = 0; i < a.length; i++) {
        if (a[i].label != undefined && a[i].label != null && a[i].label != "") {
          showCustomerForm.value = false;
          break;
        }
        console.log(a[i]);
        if (a[i].title == "所属客户") {
          a[i]["on"] = {
            focus(inject) {
              dialogCustomerCompanyNoTableVisible.value = true;
            }
          };
        }
        if (a[i].title == "请求分类") {
          a[i]["on"] = {
            focus(inject) {
              dialogRequestCategoryTableVisible.value = true;
            }
          };
        }
        if (a[i].title == "请求用户") {
          a[i]["on"] = {
            focus(inject) {
              dialogCustomerCreatedByTableVisible.value = true;
            }
          };
        }
        if (a[i].title == "位置") {
          a[i]["on"] = {
            focus(inject) {
              dialogLocationTableVisible.value = true;
            }
          };
        }
        if (a[i].attrdataDictionary != null && a[i].attrdataDictionary != undefined && a[i].attrdataDictionary != "") {
          dataFlagObj.value.push(a[i]);
          //优先级priority
          dataDictionaryItemsfindByCode(a[i].attrdataDictionary).then(res => {
            let optionList = [];
            (res as any).forEach(function (element) {
              // element["label"] = element["dname"];
              // element["value"] = element["dname"];
              //optionList.push({label:element["dname"],value:element["dcode"]})
              a[i].options.push({ label: element["dname"], value: element["dcode"] });
            });
            // a[i].options=optionList
          });
        }

        if (a[i].title == "描述") {
          edescFlag.value = true;
          continue;
        }
        if (edescFlag.value == false) {
          formCreateRulesArray.push(a[i] as any);
        } else {
          formCreateRules2Array.push(a[i] as any);
        }
      }
      formCreateRules.value = formCreateRulesArray;
      formCreateRules2.value = formCreateRules2Array;

      let attrVals = data.attrVals == undefined ? {} : data.attrVals;
      setTimeout(() => {
        formData.value.creator = data.creator == undefined ? "" : data.creator;

        formData.value.approvalNo = data.approvalNo == undefined ? "" : data.approvalNo;

        formData.value.etitle = data.etitle == undefined ? "" : data.etitle;
        formData.value.companyName = data.companyName == undefined ? "" : data.companyName;
        formData.value.companyNo = data.companyNo == undefined ? 1 : data.companyNo;
        formData.value.createdByName = data.createdByName == undefined ? "" : data.createdByName;
        formData.value.createdByNo = data.createdByNo == undefined ? "" : data.createdByNo;
        formData.value.requestCategoryName = data.requestCategoryName == undefined ? "" : data.requestCategoryName;
        formData.value.requestCategoryNo = data.requestCategoryNo == undefined ? "" : data.requestCategoryNo;
        //requestCategorySelectValue.value=data.requestCategoryName==undefined?"":data.requestCategoryName;
        //addRequestTemplateFormData.edesc= data.edesc==undefined?"":data.edesc;
        customerContent.value = data.edesc == undefined ? "" : data.edesc;
        // imodeSelectValue prioritySelectValue effectRangeSelectValue levelSelectValue seriousnessSelectValue LocationSelectValue
        formData.value.imodeNo = data.imodeNo == undefined || data.imodeNo == 0 ? "" : data.imodeNo;
        formData.value.priorityNo = data.priorityNo == undefined || data.priorityNo == 0 ? "" : data.priorityNo;
        formData.value.effectRangeNo = data.effectRangeNo == undefined || data.effectRangeNo == 0 ? "" : data.effectRangeNo;
        formData.value.levelNo = data.levelNo == undefined || data.levelNo == 0 ? "" : data.levelNo;
        formData.value.seriousnessNo = data.seriousnessNo == undefined || data.seriousnessNo == 0 ? "" : data.seriousnessNo;
        formData.value.locationName = data.locationName == undefined ? "" : data.locationName;
        formData.value.locationNos = data.locationNos == undefined || data.locationNos == 0 ? "" : data.locationNos;
        Object.keys(attrVals).forEach(key => {
          for (let i = 0; i < dataFlagObj.value.length; i++) {
            if (dataFlagObj.value[i].title == key) {
              let eavKey = dataFlagObj.value[i].field;
              if (`${attrVals[key]}` == "true") {
                formData.value[dataFlagObj.value[i].field] = true;
              } else {
                if (!Number.isNaN(Number(`${attrVals[key]}`))) {
                  if (`${attrVals[key]}` == "") {
                    formData.value[dataFlagObj.value[i].field] = `${attrVals[key]}`;
                  } else {
                    //数字
                    formData.value[dataFlagObj.value[i].field] = parseInt(`${attrVals[key]}`);
                  }
                } else {
                  //非数字
                  formData.value[dataFlagObj.value[i].field] = `${attrVals[key]}`;
                }
              }
            }
          }
        });
      }, 1500);
    });
  } else {
    showCustomerForm.value = false;
  }
};
defineExpose({
  open,
  updateData
});
</script>

<style lang="scss" scoped>
.custom-tree {
  height: 450px; /* 你想要的高度 */
  overflow-y: auto; /* 添加垂直滚动条 */
}
.messageIndex {
  z-index: 9999 !important; // 设置的值一定要比2007大，因为dialog的层级是2007
}
</style>
<style lang="scss">
.customMsgCls {
  z-index: 20010 !important;
}
</style>
